require 'logger'

require 'request'
require 'action'
require 'url_parser'
require 'path_mapper'



# === ページコントローラの基底．
#
# Author:: krdlab
#
class PageController
  attr_accessor :mapper, :logger

  def initialize
    @mapper = create_mapper
    @logger = create_logger(get_path4log)
  end

  def dispatch
    request = create_request
    begin
      action = self.send(request.action, request)
      request.update_session
      # 実行
      action.run
    rescue => e
      #error_action(e, request)
      raise e
    ensure
      # リクエストを閉じる
      request.close_session
    end
  end

  def error_action(exception, request)
    return ErrorAction.new(exception, request).run
  end

  def redirect_to(request)
    return redirect_to(request.action, request)
  end

  def redirect_to(action, request)
    return RedirectAction.new(@mapper.to_path(action), request)
  end

  def create_mapper
    return nil
  end

  def create_request
    request = Request.new
    #request.parts = parser.parse(request.url)
    logger.debug { "request.action=#{request.action}" }
    return request
  end

protected
  def create_logger(log_path)
    Logger.new(log_path, 5)
  end
end

